package fy.input.sql;

import java.io.FileInputStream;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import fy.util.MyUtil;


final class SQLReader {
	// private static Map<String, String> sqlMap = new Hashtable<String,
	// String>();
	private static Map<String, SQLBean> sqlMap = new Hashtable<String, SQLBean>();

	// private static void readSQL() {
	// try {
	// FileInputStream fis = new FileInputStream(
	// MyUtil.getRealPath(SQLReader.class) + "/query.properties");
	// Properties pps = new Properties();
	// pps.load(new FileInputStream(MyUtil.getRealPath(SQLReader.class)
	// + "/query.properties"));
	//
	// for (Enumeration<Object> e = pps.keys(); e.hasMoreElements();) {
	// String key = (String) e.nextElement();
	// String sql = pps.getProperty(key);
	// if (sql.indexOf("insert") == -1 && sql.indexOf("delete") == -1
	// && sql.indexOf("update") == -1) {
	// sql = sql.substring(1, sql.length());
	// sql = sql.substring(0, sql.length() - 1);
	// sqlMap.put(key, sql);
	// }
	// }
	//
	// pps = null;
	// fis.close();
	// fis = null;
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	private static void XMLReader() {
		try {
			FileInputStream fis = new FileInputStream(
					MyUtil.getRealPath(SQLReader.class) + "/query.xml");

			SAXReader reader = new SAXReader();
			Document doc = reader.read(fis);

			Element root = doc.getRootElement();

			for (Iterator<Element> iter = root.elementIterator(); iter
					.hasNext();) {
				SQLBean bean = new SQLBean();
				Element e = iter.next();
				String id = e.attributeValue("id");
				bean.setId(id);
				for (Iterator<Element> children = e.elementIterator(); children
						.hasNext();) {
					Element child = children.next();
					String name = child.attributeValue("id");
					String value = child.getText();
					if ("str".equals(name)) {
							bean.addStr(value);
					} else if ("is_null".equals(name)) {
						bean.setIsNull(value);
					} else if ("error".equals(name)) {
						bean.setError(value);
					} else if ("database".equals(name)) {
						bean.setDatabase(value);
					}
					child = null;
				}
				sqlMap.put(id, bean);
				bean = null;
				e = null;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SQLBean getSQL(String name) {
		if (name != null) {
			SQLBean sql = sqlMap.get(name);
			// if (sql == null) {
			XMLReader();
			sql = sqlMap.get(name);
			// }
			return sql;
		} else {
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println(getSQL("hr_rm8").getStr().get(0).replace("\n", " ").replace("\t", " "));
	}
}
